<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="题目内容" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入题目内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属科目" prop="subjectId">
        <el-select
          v-model="queryParams.subjectId"
          placeholder="请选择所属科目"
          clearable
          @change="handleSubjectChange"
        >
          <el-option
            v-for="subject in subjectList"
            :key="subject.id"
            :label="subject.name"
            :value="subject.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属课程" prop="courseId">
        <el-select
          v-model="queryParams.courseId"
          placeholder="请选择所属课程"
          clearable
          @change="handleCourseChange"
        >
          <el-option
            v-for="course in courseList"
            :key="course.id"
            :label="course.name"
            :value="course.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属章节" prop="chapterId">
        <el-select
          v-model="queryParams.chapterId"
          placeholder="请选择所属章节"
          clearable
          @change="handleChapterChange"
        >
          <el-option
            v-for="chapter in chapterList"
            :key="chapter.id"
            :label="chapter.name"
            :value="chapter.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="题目类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择题目类型"
          clearable
        >
          <el-option label="单选题" value="SINGLE" />
          <el-option label="多选题" value="MULTI" />
          <el-option label="判断题" value="JUDGE" />
        </el-select>
      </el-form-item>
      <el-form-item label="题目难度" prop="difficulty">
        <el-select
          v-model="queryParams.difficulty"
          placeholder="请选择题目难度"
          clearable
        >
          <el-option
            v-for="dict in dict.type.difficulty"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fk:question:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fk:question:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fk:question:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fk:question:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="questionList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="题目ID" width="60" align="center" prop="id" />
      <el-table-column label="题目内容" align="center" prop="title" />
      <el-table-column label="图片" align="center" prop="url" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.url" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="所属科目" align="center" prop="subjectName" />
      <el-table-column label="所属课程" align="center" prop="courseName" />
      <el-table-column label="所属章节" align="center" prop="chapterName" />
      <el-table-column label="题目类型" align="center" prop="type">
        <template slot-scope="scope">
          {{ getTypeLabel(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="题目难度" align="center" prop="difficulty">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.difficulty"
            :value="scope.row.difficulty"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="del">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.del == 1" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.del == 0" type="danger">停用</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fk:question:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.del === 1"
            icon="el-icon-setting"
            @click="handleManageOptions(scope.row)"
            v-hasPermi="['ssh:option:list']"
            >管理选项</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fk:question:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改题目管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="题目内容" prop="title">
          <el-input v-model="form.title" placeholder="请输入题目内容" />
        </el-form-item>
        <el-form-item label="图片" prop="url">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="(options) => customUpload(options)"
            :show-file-list="false"
            :before-upload="beforeUpload"
            accept="image/*"
          >
            <img v-if="form.url" :src="form.url" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="题目难度" prop="difficulty">
          <el-select
            v-model="form.difficulty"
            placeholder="请选择题目难度"
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.difficulty"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="题目类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择题目类型"
            style="width: 100%"
          >
            <el-option label="单选题" value="SINGLE" />
            <el-option label="多选题" value="MULTI" />
            <el-option label="判断题" value="JUDGE" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属科目" prop="subjectName">
          <el-select
            v-model="form.subjectId"
            placeholder="请选择所属科目"
            style="width: 100%"
            @change="handleFormSubjectChange"
          >
            <el-option
              v-for="subject in subjectList"
              :key="subject.id"
              :label="subject.name"
              :value="subject.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属课程" prop="courseName">
          <el-select
            v-model="form.courseId"
            placeholder="请选择所属课程"
            clearable
            style="width: 100%"
            @change="handleFormCourseChange"
          >
            <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属章节" prop="chapterName">
          <el-select
            v-model="form.chapterId"
            placeholder="请选择所属章节"
            clearable
            style="width: 100%"
            @change="handleFormChapterChange"
          >
            <el-option
              v-for="chapter in chapterList"
              :key="chapter.id"
              :label="chapter.name"
              :value="chapter.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目状态" prop="del" v-if="open1">
          <el-select
            v-model="form.del"
            placeholder="请选择题目状态"
            clearable
            style="width: 100%"
          >
            <el-option :key="1" label="正常" :value="1" />
            <el-option :key="0" label="停用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 管理选项对话框 -->
    <el-dialog
      title="管理选项"
      :visible.sync="optionOpen"
      width="500px"
      append-to-body
    >
      <el-form label-width="100px" style="margin-bottom: 20px">
<!--        <el-form-item label="题目ID">-->
<!--          <el-input-->
<!--            :value="currentQuestion && currentQuestion.id"-->
<!--            readonly-->
<!--            class="readonly-input"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item label="题目内容">
          <el-input
            :value="currentQuestion && currentQuestion.title"
            readonly
            type="textarea"
            :rows="2"
            class="readonly-input"
          />
        </el-form-item>
      </el-form>
      <el-form
        ref="optionFormRef"
        :model="optionForm"
        :rules="optionRules"
        label-width="100px"
      >
        <el-form-item label="选项A" prop="optionA">
          <el-input
            v-model="optionForm.optionA"
            placeholder="请输入选项A内容"
          />
        </el-form-item>
        <el-form-item label="选项B" prop="optionB">
          <el-input
            v-model="optionForm.optionB"
            placeholder="请输入选项B内容"
          />
        </el-form-item>
        <el-form-item label="选项C" prop="optionC">
          <el-input
            v-model="optionForm.optionC"
            placeholder="请输入选项C内容"
          />
        </el-form-item>
        <el-form-item label="选项D" prop="optionD">
          <el-input
            v-model="optionForm.optionD"
            placeholder="请输入选项D内容"
          />
        </el-form-item>
        <el-form-item label="正确答案" prop="correctOptions">
          <el-select
            v-model="optionForm.correctOptions"
            placeholder="请选择正确答案"
            style="width: 100%"
          >
            <el-option label="A" value="A" />
            <el-option label="B" value="B" />
            <el-option label="C" value="C" />
            <el-option label="D" value="D" />
          </el-select>
        </el-form-item>
        <el-form-item label="题目解析" prop="analysis">
          <el-input
            type="textarea"
            v-model="optionForm.analysis"
            placeholder="请输入题目解析"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitOptionForm">确 定</el-button>
        <el-button @click="cancelOption">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listQuestion,
  getQuestion,
  delQuestion,
  addQuestion,
  updateQuestion,
} from "@/api/fk/question";
import {
  getQuestionOptionByQuestionId,
  addQuestionOption,
  updateQuestionOption,
} from "@/api/ssh/questionOption";
import request from "@/utils/request";
import { uploadFile } from "@/api/oss";

export default {
  name: "Question",
  dicts: ["difficulty"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目管理表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      // 科目列表
      subjectList: [],
      // 课程列表
      courseList: [],
      // 章节列表
      chapterList: [],
      // 是否显示管理选项对话框
      optionOpen: false,
      // 当前题目信息
      currentQuestion: null,
      // 选项表单数据
      optionForm: {
        id: null,
        questionId: null,
        optionA: "",
        optionB: "",
        optionC: "",
        optionD: "",
        correctOptions: "",
        analysis: "",
      },
      // 选项表单校验规则
      optionRules: {
        optionA: [
          { required: true, message: "选项A不能为空", trigger: "blur" },
        ],
        optionB: [
          { required: true, message: "选项B不能为空", trigger: "blur" },
        ],
        optionC: [
          { required: true, message: "选项C不能为空", trigger: "blur" },
        ],
        optionD: [
          { required: true, message: "选项D不能为空", trigger: "blur" },
        ],
        correctOptions: [
          { required: true, message: "正确答案不能为空", trigger: "blur" },
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        subjectId: null,
        courseId: null,
        chapterId: null,
        type: null,
        difficulty: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "题目内容不能为空", trigger: "blur" },
        ],
        courseId: [
          { required: true, message: "所属课程不能为空", trigger: "change" },
        ],
        chapterId: [
          { required: true, message: "所属章节不能为空", trigger: "change" },
        ],
        type: [
          { required: true, message: "题目类型不能为空", trigger: "change" },
        ],
        difficulty: [
          { required: true, message: "题目难度不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.initData();
  },
  methods: {
    /** 初始化数据 */
    async initData() {
      try {
        // 先获取科目、课程和章节列表
        await this.getSubjectList();
        await this.getCourseList();
        await this.getChapterList(); // 初始化时获取所有章节
        // 最后获取题目列表
        this.getList();
      } catch (error) {
        console.error("初始化数据失败:", error);
        this.$message.error("初始化数据失败，请刷新页面重试");
      }
    },

    /** 获取科目列表 */
    getSubjectList() {
      // 调用科目接口获取数据
      return request({
        url: "/ssh/subject/allNameAndId1",
        method: "get",
      })
        .then((response) => {
          console.log(response);
          if (response.code === 200) {
            this.subjectList = response.data || [];
          }
          return response;
        })
        .catch((error) => {
          console.error("获取科目列表失败:", error);
          this.subjectList = [];
          throw error;
        });
    },

    /** 获取课程列表 */
    getCourseList() {
      // 初始化时获取所有课程
      return request({
        url: "/ssh/course/listBySubjectIdNoPage",
        method: "get",
        params: { subjectId: null }, // 传入null获取所有课程
      })
        .then((response) => {
          if (response.code === 200) {
            this.courseList = response.data || [];
            console.log('初始化获取所有课程:', this.courseList);
          }
          return response;
        })
        .catch((error) => {
          console.error("获取所有课程失败:", error);
          this.courseList = [];
          throw error;
        });
    },

    /** 获取章节列表 */
    getChapterList() {
      // 初始化时获取所有章节
      return request({
        url: "/ssh/chapter/listByCourseIdNoPage",
        method: "get",
        params: { courseId: null }, // 传入null获取所有章节
      })
        .then((response) => {
          if (response.code === 200) {
            this.chapterList = response.data || [];
            console.log('初始化获取所有章节:', this.chapterList);
          }
          return response;
        })
        .catch((error) => {
          console.error("获取所有章节失败:", error);
          this.chapterList = [];
          throw error;
        });
    },

    /** 科目变化处理 */
    handleSubjectChange(subjectId) {
      // 当科目变化时，清空课程和章节选择并重新获取课程列表
      this.queryParams.courseId = null;
      this.queryParams.chapterId = null;
      this.courseList = [];
      this.chapterList = [];
      if (subjectId) {
        this.getCourseListBySubject(subjectId);
      } else {
        this.courseList = [];
      }
    },

    /** 课程变化处理 */
    handleCourseChange(courseId) {
      // 当课程变化时，清空章节选择并重新获取章节列表
      this.queryParams.chapterId = null;
      this.chapterList = [];
      if (courseId) {
        this.getChapterListByCourse(courseId);
      } else {
        this.chapterList = [];
      }
    },

    /** 章节变化处理 */
    handleChapterChange(chapterId) {
      // 当章节变化时，自动设置对应的课程和科目
      if (chapterId) {
        this.getCourseAndSubjectByChapterId(chapterId);
      } else {
        this.queryParams.chapterId = null;
      }
    },

    /** 根据章节ID获取课程和科目信息 */
    getCourseAndSubjectByChapterId(chapterId) {
      console.log('根据章节ID获取课程和科目信息:', chapterId);

      // 从章节列表中查找对应的章节信息
      const selectedChapter = this.chapterList.find(chapter => chapter.id === chapterId);
      if (selectedChapter) {
        console.log('找到选中的章节:', selectedChapter);

        // 如果章节对象中有课程信息，直接使用
        if (selectedChapter.courseId) {
          this.queryParams.courseId = selectedChapter.courseId;
          console.log('根据章节自动设置课程ID:', selectedChapter.courseId);

          // 继续查询课程对应的科目
          this.getSubjectByCourseId(selectedChapter.courseId);
        } else if (selectedChapter.course && selectedChapter.course.id) {
          // 如果章节对象中有课程对象
          this.queryParams.courseId = selectedChapter.course.id;
          console.log('根据章节自动设置课程ID:', selectedChapter.course.id);

          // 继续查询课程对应的科目
          this.getSubjectByCourseId(selectedChapter.course.id);
        } else {
          // 如果章节对象中没有课程信息，需要调用API查询
          this.queryCourseByChapterId(chapterId);
        }
      } else {
        console.warn('未找到对应的章节信息，章节ID:', chapterId);
      }
    },

    /** 根据课程ID获取科目信息 */
    getSubjectByCourseId(courseId) {
      console.log('根据课程ID获取科目信息:', courseId);

      // 从课程列表中查找对应的课程信息
      const selectedCourse = this.courseList.find(course => course.id === courseId);
      if (selectedCourse) {
        console.log('找到选中的课程:', selectedCourse);

        // 如果课程对象中有科目信息，直接使用
        if (selectedCourse.subjectId) {
          this.queryParams.subjectId = selectedCourse.subjectId;
          console.log('根据课程自动设置科目ID:', selectedCourse.subjectId);
        } else if (selectedCourse.subject && selectedCourse.subject.id) {
          // 如果课程对象中有科目对象
          this.queryParams.subjectId = selectedCourse.subject.id;
          console.log('根据课程自动设置科目ID:', selectedCourse.subject.id);
        } else {
          // 如果课程对象中没有科目信息，需要调用API查询
          this.querySubjectByCourseId(courseId);
        }
      } else {
        console.warn('未找到对应的课程信息，课程ID:', courseId);
      }
    },

    /** 调用API查询课程对应的科目 */
    querySubjectByCourseId(courseId) {
      console.log('调用API查询课程对应的科目:', courseId);

      // 这里可以调用一个专门的API来获取课程对应的科目信息
      // 或者通过课程详情接口获取
      request({
        url: "/ssh/course/" + courseId,
        method: "get",
      })
        .then((response) => {
          if (response.code === 200 && response.data) {
            const courseData = response.data;
            console.log('课程详情数据:', courseData);

            if (courseData.subjectId) {
              this.queryParams.subjectId = courseData.subjectId;
              console.log('通过API查询到课程对应的科目ID:', courseData.subjectId);
            } else if (courseData.subject && courseData.subject.id) {
              this.queryParams.subjectId = courseData.subject.id;
              console.log('通过API查询到课程对应的科目ID:', courseData.subject.id);
            }
          }
        })
        .catch((error) => {
          console.error('查询课程详情失败:', error);
        });
    },

    /** 调用API查询章节对应的课程 */
    queryCourseByChapterId(chapterId) {
      console.log('调用API查询章节对应的课程:', chapterId);

      // 调用章节详情接口获取课程信息
      request({
        url: "/ssh/chapter/" + chapterId,
        method: "get",
      })
        .then((response) => {
          if (response.code === 200 && response.data) {
            const chapterData = response.data;
            console.log('章节详情数据:', chapterData);

            if (chapterData.courseId) {
              this.queryParams.courseId = chapterData.courseId;
              console.log('通过API查询到章节对应的课程ID:', chapterData.courseId);

              // 继续查询课程对应的科目
              this.getSubjectByCourseId(chapterData.courseId);
            } else if (chapterData.course && chapterData.course.id) {
              this.queryParams.courseId = chapterData.course.id;
              console.log('通过API查询到章节对应的课程ID:', chapterData.course.id);

              // 继续查询课程对应的科目
              this.getSubjectByCourseId(chapterData.course.id);
            }
          }
        })
        .catch((error) => {
          console.error('查询章节详情失败:', error);
        });
    },

    /** 根据科目获取课程列表 */
    getCourseListBySubject(subjectId) {
      // 清空课程列表
      this.courseList = [];

      if (!subjectId) {
        return;
      }

      // 调用后端接口获取指定科目的课程列表
      request({
        url: "/ssh/course/listBySubjectIdNoPage",
        method: "get",
        params: { subjectId: subjectId },
      })
        .then((response) => {
          if (response.code === 200) {
            // 使用不分页接口，直接获取data
            this.courseList = response.data || [];
          }
        })
        .catch((error) => {
          console.error("根据科目获取课程列表失败:", error);
          this.courseList = [];
        });
    },

    /** 根据课程获取章节列表 */
    getChapterListByCourse(courseId) {
      // 清空章节列表
      this.chapterList = [];

      if (!courseId) {
        return;
      }

      // 调用后端接口获取指定课程的章节列表
      request({
        url: "/ssh/chapter/listByCourseIdNoPage",
        method: "get",
        params: { courseId: courseId },
      })
        .then((response) => {
          if (response.code === 200) {
            // 使用不分页接口，直接获取data
            this.chapterList = response.data || [];
          }
        })
        .catch((error) => {
          console.error("根据课程获取章节列表失败:", error);
          this.chapterList = [];
        });
    },

    /** 表单中科目变化处理 */
    handleFormSubjectChange(subjectId) {
      // 当表单中科目变化时，清空课程和章节选择并重新获取课程列表
      this.form.courseId = null;
      this.form.chapterId = null;
      this.courseList = [];
      this.chapterList = [];
      if (subjectId) {
        this.getCourseListBySubject(subjectId);
      } else {
        this.courseList = [];
      }
    },

    /** 表单中课程变化处理 */
    handleFormCourseChange(courseId) {
      // 当表单中课程变化时，清空章节选择并重新获取章节列表
      this.form.chapterId = null;
      this.chapterList = [];
      if (courseId) {
        this.getChapterListByCourse(courseId);
      } else {
        this.chapterList = [];
      }
    },

    /** 表单中章节变化处理 */
    handleFormChapterChange(chapterId) {
      // 当表单中章节变化时，自动设置对应的课程和科目
      if (chapterId) {
        this.getCourseAndSubjectByChapterIdForForm(chapterId);
      } else {
        this.form.chapterId = null;
      }
    },

    /** 表单中根据章节ID获取课程和科目信息 */
    getCourseAndSubjectByChapterIdForForm(chapterId) {
      console.log('表单中根据章节ID获取课程和科目信息:', chapterId);

      // 从章节列表中查找对应的章节信息
      const selectedChapter = this.chapterList.find(chapter => chapter.id === chapterId);
      if (selectedChapter) {
        console.log('找到选中的章节:', selectedChapter);

        // 如果章节对象中有课程信息，直接使用
        if (selectedChapter.courseId) {
          this.form.courseId = selectedChapter.courseId;
          console.log('根据章节自动设置课程ID:', selectedChapter.courseId);

          // 继续查询课程对应的科目
          this.getSubjectByCourseIdForForm(selectedChapter.courseId);
        } else if (selectedChapter.course && selectedChapter.course.id) {
          // 如果章节对象中有课程对象
          this.form.courseId = selectedChapter.course.id;
          console.log('根据章节自动设置课程ID:', selectedChapter.course.id);

          // 继续查询课程对应的科目
          this.getSubjectByCourseIdForForm(selectedChapter.course.id);
        } else {
          // 如果章节对象中没有课程信息，需要调用API查询
          this.queryCourseByChapterIdForForm(chapterId);
        }
      } else {
        console.warn('未找到对应的章节信息，章节ID:', chapterId);
      }
    },

    /** 表单中根据课程ID获取科目信息 */
    getSubjectByCourseIdForForm(courseId) {
      console.log('表单中根据课程ID获取科目信息:', courseId);

      // 从课程列表中查找对应的课程信息
      const selectedCourse = this.courseList.find(course => course.id === courseId);
      if (selectedCourse) {
        console.log('找到选中的课程:', selectedCourse);

        // 如果课程对象中有科目信息，直接使用
        if (selectedCourse.subjectId) {
          this.form.subjectId = selectedCourse.subjectId;
          console.log('根据课程自动设置科目ID:', selectedCourse.subjectId);
        } else if (selectedCourse.subject && selectedCourse.subject.id) {
          // 如果课程对象中有科目对象
          this.form.subjectId = selectedCourse.subject.id;
          console.log('根据课程自动设置科目ID:', selectedCourse.subject.id);
        } else {
          // 如果课程对象中没有科目信息，需要调用API查询
          this.querySubjectByCourseIdForForm(courseId);
        }
      } else {
        console.warn('未找到对应的课程信息，课程ID:', courseId);
      }
    },

    /** 表单中调用API查询课程对应的科目 */
    querySubjectByCourseIdForForm(courseId) {
      console.log('表单中调用API查询课程对应的科目:', courseId);

      request({
        url: "/ssh/course/" + courseId,
        method: "get",
      })
        .then((response) => {
          if (response.code === 200 && response.data) {
            const courseData = response.data;
            console.log('课程详情数据:', courseData);

            if (courseData.subjectId) {
              this.form.subjectId = courseData.subjectId;
              console.log('通过API查询到课程对应的科目ID:', courseData.subjectId);
            } else if (courseData.subject && courseData.subject.id) {
              this.form.subjectId = courseData.subject.id;
              console.log('通过API查询到课程对应的科目ID:', courseData.subject.id);
            }
          }
        })
        .catch((error) => {
          console.error('查询课程详情失败:', error);
        });
    },

    /** 表单中调用API查询章节对应的课程 */
    queryCourseByChapterIdForForm(chapterId) {
      console.log('表单中调用API查询章节对应的课程:', chapterId);

      request({
        url: "/ssh/chapter/" + chapterId,
        method: "get",
      })
        .then((response) => {
          if (response.code === 200 && response.data) {
            const chapterData = response.data;
            console.log('章节详情数据:', chapterData);

            if (chapterData.courseId) {
              this.form.courseId = chapterData.courseId;
              console.log('通过API查询到章节对应的课程ID:', chapterData.courseId);

              // 继续查询课程对应的科目
              this.getSubjectByCourseIdForForm(chapterData.courseId);
            } else if (chapterData.course && chapterData.course.id) {
              this.form.courseId = chapterData.course.id;
              console.log('通过API查询到章节对应的课程ID:', chapterData.course.id);

              // 继续查询课程对应的科目
              this.getSubjectByCourseIdForForm(chapterData.course.id);
            }
          }
        })
        .catch((error) => {
          console.error('查询章节详情失败:', error);
        });
    },

    /** 查询题目管理列表 */
    getList() {
      this.loading = true;
      listQuestion(this.queryParams)
        .then((response) => {
          this.questionList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((error) => {
          console.error("获取题目列表失败:", error);
          this.loading = false;
          this.$message.error("获取题目列表失败");
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        url: null,
        subjectId: null,
        courseId: null,
        chapterId: null,
        type: null,
        difficulty: null,
        createTime: null,
        del: 1, // 默认状态为正常
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 重置科目和课程相关数据
      this.queryParams.subjectId = null;
      this.queryParams.courseId = null;
      this.queryParams.chapterId = null;
      this.courseList = [];
      this.chapterList = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.open1 = false;
      this.title = "添加题目管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getQuestion(id).then((response) => {
        this.form = response.data;
        console.log('修改题目，获取到的数据:', this.form);

        // 根据科目ID获取课程列表
        if (this.form.subjectId) {
          this.getCourseListBySubject(this.form.subjectId);
        }

        // 根据课程ID获取章节列表
        if (this.form.courseId) {
          this.getChapterListByCourse(this.form.courseId);
        }

        this.open = true;
        this.open1 = true;
        this.title = "修改题目管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateQuestion(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestion(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除题目管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delQuestion(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 管理选项按钮操作 */
    handleManageOptions(row) {
      console.log("管理选项按钮点击，题目信息:", row);
      // 保存当前题目信息
      this.currentQuestion = row;
      // 设置题目ID到表单
      this.optionForm.questionId = row.id;
      // 重置选项表单（会保持questionId）
      this.resetOptionForm();
      // 查询是否已存在选项数据
      this.queryQuestionOptions(row.id);
      // 显示管理选项对话框
      this.optionOpen = true;
    },

    /** 查询题目选项 */
    queryQuestionOptions(questionId) {
      console.log("查询题目选项，题目ID:", questionId);
      getQuestionOptionByQuestionId(questionId)
        .then((response) => {
          console.log("查询结果:", response.data);
          if (response.data) {
            const data = response.data;
            // 智能更新表单字段：只更新非null/undefined的值
            const fields = [
              "id",
              "optionA",
              "optionB",
              "optionC",
              "optionD",
              "correctOptions",
              "analysis",
            ];
            fields.forEach((field) => {
              if (data[field] != null) {
                // != null 同时检查 null 和 undefined
                this.optionForm[field] = data[field];
              }
            });
            // 确保questionId正确设置
            if (!data.questionId) {
              this.optionForm.questionId = questionId;
            }
            console.log("回显后的表单数据:", this.optionForm);
          } else {
            console.log("没有查询到选项数据，保持表单为空");
          }
        })
        .catch((error) => {
          console.error("查询失败:", error);
        });
    },

    /** 重置选项表单 */
    resetOptionForm() {
      // 保存questionId，重置其他字段
      const questionId = this.optionForm.questionId || this.currentQuestion?.id;
      this.optionForm = {
        id: null,
        questionId,
        optionA: "",
        optionB: "",
        optionC: "",
        optionD: "",
        correctOptions: "",
        analysis: "",
      };
      // 清除表单验证状态
      this.$nextTick(() => {
        this.$refs.optionFormRef?.clearValidate();
      });
    },

    /** 取消选项操作 */
    cancelOption() {
      this.optionOpen = false;
      this.resetOptionForm();
    },

    /** 提交选项表单 */
    submitOptionForm() {
      this.$refs.optionFormRef.validate((valid) => {
        if (!valid) return;
        const isUpdate = !!this.optionForm.id;
        const apiCall = isUpdate ? updateQuestionOption : addQuestionOption;
        const successMsg = isUpdate ? "修改成功" : "新增成功";

        apiCall(this.optionForm)
          .then(() => {
            this.$modal.msgSuccess(successMsg);
            this.optionOpen = false;
            this.resetOptionForm();
          })
          .catch((error) => {
            console.error(`${isUpdate ? "修改" : "新增"}失败:`, error);
            this.$modal.msgError("操作失败");
          });
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "fk/question/export",
        {
          ...this.queryParams,
        },
        `question_${new Date().getTime()}.xlsx`
      );
    },

    /** 获取题目类型的中文标签 */
    getTypeLabel(type) {
      const typeMap = {
        'SINGLE': '单选题',
        'MULTI': '多选题',
        'JUDGE': '判断题'
      };
      return typeMap[type] || type || '未知类型';
    },
    // 图片上传相关方法
    beforeUpload(file) {
      // 文件类型验证
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      
      // 文件大小验证 (5MB)
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!');
        return false;
      }
      
      return true;
    },
    // 自定义上传方法，使用oss.js中的uploadFile
    async customUpload(options) {
      try {
        const { file } = options;
        
        // 显示上传进度
        this.$modal.loading("正在上传图片，请稍候...");
        
        // 创建FormData
        const formData = new FormData();
        formData.append("file", file);
        
        // 调用oss.js中的uploadFile方法
        const response = await uploadFile(formData);
        
        // 调试信息：打印完整的响应数据
        console.log('OSS上传响应:', response);
        
        if (response.code === 200) {
          this.$message.success("图片上传成功");
          // 注意：后端返回的url在response根级别，不是在data中
          const imageUrl = response.url || response.data?.url;
          if (imageUrl) {
            this.form.url = imageUrl;
          } else {
            console.error('响应中没有找到图片URL:', response);
            this.$message.error("上传成功但未获取到图片URL");
          }
        } else {
          this.$message.error(response.msg || "上传失败");
        }
      } catch (error) {
        console.error('上传失败:', error);
        this.$message.error("上传失败：" + (error.message || '未知错误'));
      } finally {
        this.$modal.closeLoading();
      }
      
      // 通知el-upload组件上传完成
      options.onSuccess();
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}

.avatar {
  width: 148px;
  height: 148px;
  display: block;
  object-fit: cover;
}
</style>
